package com.ajl.wx.module.wechat.controller;

import com.ajl.wx.beans.po.WechatUserPO;
import com.ajl.wx.beans.vo.ResultApi;
import com.ajl.wx.config.WebApplicationProperties;
import com.ajl.wx.global.ClientConfig;
import com.ajl.wx.module.wechat.service.impl.TbWechatUserServiceImpl;
import com.ajl.wx.utils.ResultApiUtil;
import com.ajl.wx.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/user")
public class UserLoginController {

    @Autowired
    TbWechatUserServiceImpl wechatService;


    @Autowired
    WebApplicationProperties webApplicationProperties;

    /**
     * 用户登录
     * @param openId
     * @param jsCode
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResultApi login(
            @RequestParam(value = "openId", required = false, defaultValue = "") String openId,
            @RequestParam(value = "jsCode") String jsCode,
            WechatUserPO user) {
        if (StringUtils.isNull(openId)) {
            openId = wechatService.code2Session(jsCode);
        }
        if (wechatService.getById(openId) != null) {
            user.setWechatId(openId);
            wechatService.updateById(user);
        } else {
            user.setWechatId(openId);
            wechatService.save(user);
        }
        ClientConfig.clientConfigurationMap.put("openId",openId);
        return ResultApiUtil.success("OK", ClientConfig.clientConfigurationMap);
    }
}
